iT邦幫忙

2022 iThome 鐵人賽

DAY 22
0

題目(5kyu):

ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 >letters after it in the alphabet. ROT13 is an example of the Caesar cipher.

Create a function that takes a string and returns the string ciphered with Rot13. If >there are numbers or special characters included in the string, they should be returned >as they are. Only letters from the latin/english alphabet should be shifted, like in >the original Rot13 "implementation".

Please note that using encode is considered cheating.

解題思路

題目理解:設計一函數代入一字串,返還經過Rot13規則加密後之字串,詳細可以參考https://zh.m.wikipedia.org/zh-tw/ROT13

這邊參考Day3提到利用upper()&lower()來判斷是否為非字母字元的方法來解題。

def rot13(message):
    letters = "abcdefghijklmnopqrstuvwxyz"
    reslut = ""
    #逐一檢驗message字元
    for i in message:
        #若一字元其upper()&lower()結果相同則為非字母字元
        if i.upper() !=i.lower():
            #若該字母在letters內代表為小寫
            if i in letters:
                ind = letters.index(i)+13
                if ind>25: 
                    ind -= 26
                #另i等於修改後字母
                i = letters[ind]
                print(i,ind)
            #若該字母不在letters內則必為大寫
            else:
                ind = letters.index(i.lower())+13
                if ind>25:
                    ind -= 26
                i = letters[ind].upper()
        reslut += i
    return reslut

上一篇
[Day21] Codewars >>> Luck check (Python)
下一篇
[Day23] Codewars >>> Numbers and its Reversal Having Same Prime Factors. (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言